from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import joblib
import os

# 加载数字数据集
digits = load_digits()
X, y = digits.data, digits.target

# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_acc = 0.0
best_k = None
best_model = None

# 初始化一个列表以存储每个k值的准确率
accuracies = []

# 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
for k in range(1, 41):
    knn = KNeighborsClassifier(n_neighbors=k, n_jobs=-1)
    knn.fit(X_train, y_train)
    preds = knn.predict(X_test)
    acc = accuracy_score(y_test, preds)
    accuracies.append(acc)
    if acc > best_acc:
        best_acc = acc
        best_k = k
        best_model = knn

# 将最佳KNN模型保存到二进制文件
if best_model is not None:
    try:
        base_dir = os.path.dirname(__file__)
    except NameError:
        # 在交互式环境（如 REPL/Jupyter）中 __file__ 可能不存在，回退到当前工作目录
        base_dir = os.getcwd()
    save_path = os.path.join(base_dir, "best_knn_model.pkl")
    joblib.dump(best_model, save_path)

# 打印最佳准确率和相应的k值
print(f"最佳准确率: {best_acc:.4f}，对应的 k 值: {best_k}")